package com.xuecheng.base.exception;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {
    //处理自定义异常
    @ResponseBody
    @ExceptionHandler(XueChengPlusException.class)//标记要拦截什么异常
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)//这个注解是返回什么状态码
    public RestErrorResponse customException(XueChengPlusException e){
        log.error("系统异常{}",e.getErrMessage(),e);
        return new RestErrorResponse(e.getErrCode(),e.getErrMessage());
    }

    //处理其它异常
    @ResponseBody
    @ExceptionHandler(Exception.class)//标记要拦截什么异常
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)//这个注解是返回什么状态码
    public RestErrorResponse exception(Exception e){
        log.error("系统异常{}",e.getMessage(),e);
        if(e.getMessage().equals("不允许访问")){
            return new RestErrorResponse("您没有权限操作此功能");
        }
        return new RestErrorResponse(CommonError.UNKOWN_ERROR.getErrMessage());
    }

    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public RestErrorResponse methodArgumentNotValidException(
            MethodArgumentNotValidException e){
        BindingResult bindingResult = e.getBindingResult();
        List<String> errors = new ArrayList<>();
        bindingResult.getFieldErrors().stream().forEach(item -> {
            errors.add(item.getDefaultMessage());
        });
        String errorMessage = StringUtils.join(errors,",");
        log.error("系统异常{}",errorMessage,e);
        return new RestErrorResponse(errorMessage);
    }
}
